import { getLayoutProps } from "@/common/layout/getProps";
import { DeleteOutlined, DownloadOutlined, EditOutlined, PlusOutlined } from "@ant-design/icons";
import { PageContainer } from "@ant-design/pro-layout";
import {
  Button,
  Col,
  DatePicker, Descriptions, Divider,
  Form,
  Input,
  InputNumber, message, Modal,
  Row, Select, Space,
  Table,
  type TableColumnsType,
  type TableProps
} from "antd";
import Router from "next/router";
import dayjs from "dayjs";
import { useRouter } from "next/router";
import { type FC, type HTMLAttributes, type Key, type PropsWithChildren, useEffect, useState } from "react";
import GlobalClasses from "@/styles/globalClasses.module.scss";
import styles from "./index.module.scss";
import { http } from "@/utils/request";

type TableDataType = {
  field1: string;
  field2: string;
  field3: string;
  field4: string;
  field5: string;
  field6: string;
  field7: string;
  field8: string;
  field9: string;
}

const { confirm } = Modal;
export const EmployeePointsApplyCU = () => {
  const router = useRouter();
  const { query } = router;
  const { id, type } = query;
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [applicationData, setApplicationData] = useState<Partial<Record<string, any>>[]>([]);
  const [open, setOpen] = useState<boolean>(false);
  const [currentEdit, setCurrentEdit] = useState<Partial<TableDataType>>({});
  const [evaluPersionType,setEvaluPersionType] = useState(1);
  const [editIndex,setEditIndex] = useState(null);
  const [projectList,setProjectList] = useState([]);
  const [projectName,setProjectName] = useState('');
  const [projectCode,setProjectCode] = useState('');

  const isAdd = !id && !type;
  const isEdit = !!id && !type;
  const isDetail = !!id && (type === "detail");

  const applicationColumns: TableColumnsType = [
    {
      align: "center",
      title: "序号",
      width: 60,
      key: "index",
      render: (_text: string, _record, index: number) => {
        return index + 1
      }
    },
    {
      align: "center",
      title: "项目名称",
      dataIndex: "itemName",
      width: 200
    },
    {
      align: "center",
      title: "项目内容",
      dataIndex: "itemDesc",
      width: 200
    },
    {
      align: "center",
      title: "表彰情况",
      dataIndex: "praiseDesc",
      width: 200
    },
    {
      align: "center",
      title: "完成情况",
      dataIndex: "finishDesc",
      width: 200
    },
    {
      align: "center",
      title: "申请分数",
      dataIndex: "reqScore",
      width: 100
    },
    {
      align: "center",
      title: "申请说明",
      dataIndex: "reqDesc",
      width: 200
    }
  ]
  const operateColumns:TableColumnsType = [
    {
      title: "操作",
      width:200,
      align:'center',
      render: (_, record,index) => {
        return (
          <>
          <Button type={'link'} onClick={()=>{
              editForm.resetFields();
              getProjectItem();
              const newObj = JSON.parse(JSON.stringify(record));
              setCurrentEdit(newObj);
              setEditIndex(index);
              editForm.setFieldsValue(applicationData.find(item => (item.workContent === record.workContent))!)
              setOpen(true);
            }}>编辑</Button>
            <Button type={'link'} danger onClick={()=>{
              if(isEdit){
                confirm({
                  title: '提示?',
                  content: '此操作将永久删除该数据，是否继续?',
                  onOk() {
                    delApplicationData(record.id);
                  },
                });
              }else{
                const newArr = JSON.parse(JSON.stringify(applicationData));
                newArr.splice(index,1);
                setApplicationData(newArr);
              }
            }}>删除</Button>
          </>
          )
        }
    }
  ]
  const save = async() => {
    const values = await form.validateFields()
    switch (evaluPersionType) {
      case 1:
        values.evaluPersion = dayjs(values.evaluPersion).format('YYYY');
        break;
      case 2:
        values.evaluPersion = dayjs(values.evaluPersion).format('YYYY')+ '-Q' + dayjs(dayjs(values.evaluPersion).format('YYYY-MM-DD')).quarter()
        break;
      case 3:
        values.evaluPersion = dayjs(values.evaluPersion).format('YYYY-MM');
        break;
      default:
        break;
    }
    const addFormData = {
      ...values,
      personId:'1',
      deptId:'1',
      isSubmit:false,
      pmFractionApplyItemQueries:applicationData
    }
    if(isAdd){
      addSave(addFormData)
    }
    if(isEdit){
      editSave(addFormData)
    }
  }
  const submit = async() => {
    const values = await form.validateFields()
    switch (evaluPersionType) {
      case 1:
        values.evaluPersion = dayjs(values.evaluPersion).format('YYYY');
        break;
      case 2:
        values.evaluPersion = dayjs(values.evaluPersion).format('YYYY')+ '-Q' + dayjs(dayjs(values.evaluPersion).format('YYYY-MM-DD')).quarter()
        break;
      case 3:
        values.evaluPersion = dayjs(values.evaluPersion).format('YYYY-MM');
        break;
      default:
        break;
    }
    const addFormData = {
      ...values,
      personId:'1',
      deptId:'1',
      isSubmit:true,
      pmFractionApplyItemQueries:applicationData
    }
    if(isAdd){
      addSave(addFormData)
    }
    if(isEdit){
      editSave(addFormData)
    }
  }
  //新增接口
  const addSave = async(formData:object) =>{
    try {
      const res = await http.post({
        url:'/PmFractionApply/savePmFractionApply',
        data:formData,
      })
      if(res.code == 200){
        message.success('员工加减分申请新增成功!');
        Router.push('/performanceAppraise/employeePointsApply');
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //编辑接口
  const editSave = async(formData:object) =>{
    try {
      const res = await http.post({
        url:'/PmFractionApply/updatePmFractionApply',
        data:{id,...formData,}
      })
      if(res.code == 200){
        message.success('员工加减分申请修改成功!');
        Router.push('/performanceAppraise/employeePointsApply');
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  
  const handleOk = async() => {
    const values = await editForm.validateFields()
    if(values){
      values.itemName = projectName;
      values.itemCode = projectCode;
      const newData = JSON.parse(JSON.stringify(applicationData));
      if(JSON.stringify(currentEdit) === "{}"){
        newData.push(values);
      }else{
        for (const key in values) {
          if (key in newData[editIndex]) {
            newData[editIndex][key] = values[key];
          }
        }
      }
      setApplicationData(newData);
      setCurrentEdit({}); 
      setOpen(false);
    }
  }

  const handleCancel = () => {
    setCurrentEdit({});
    setOpen(false);
  }
  
  //获取项目下拉列表
  const getProjectItem = async()=>{
    try {
      const res = await http.get({
        url:'/PmPlusMinusScoreDictionary/qryDropDownOptions',
      })
      if(res.code == 200){
        applicationData.forEach(aItem => {
          res.data.forEach(bItem => {
            bItem.id = String(bItem.id)
            if (aItem.itemId == bItem.id) {
              bItem.disabled = true;
            }
          });
        });
        setProjectList(res.data.map(item=>({value:item.id,label:item.projectName,projectDescription:item.projectDescription,code:item.projectCode,disabled:item.disabled?true:false})))
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }
  //获取员工加减分申请详情数据
  const getDetailsData =async()=>{
    try {
      const res = await http.get({
        url:'/PmFractionApply/pmFractionApplyDoneList',
        params:{applyId:id}
      })
      if(res.code == 200){
        const data = JSON.parse(JSON.stringify(res.rows[0]));
        switch (data.evaluFrequency) {
          case 'YEAR'://年
          setEvaluPersionType(1);
          data.evaluPersion = dayjs().year(Number(data.evaluPersion));
            break;
          case 'QUARTER'://季度
          setEvaluPersionType(2);
          const [year, quarter] = data.evaluPersion.split('-Q');// 使用 dayjs 创建一个日期对象，并设置到季度
          data.evaluPersion = dayjs().year(Number(year)).quarter(Number(quarter));
            break;
          case 'MONTH'://月
          setEvaluPersionType(3);
          const [years, month] = data.evaluPersion.split('-');
          data.evaluPersion = dayjs().year(Number(years)).month(Number(month));
            break;
          default:
            break;
        }
        setApplicationData(data.pmFractionApplyItemVos)
        form.setFieldsValue(data);
      }else{
        message.error(res.msg);
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  }

  useEffect(() => {
    if (isEdit || isDetail) {
      getDetailsData()
    } else {
      form.setFieldsValue({})
      form.setFieldValue('personName','张三');
      form.setFieldValue('deptName','财务部门');
    }
  }, []);
  return (
    <>
      <PageContainer header={{
        title: false
      }}>
        <div className={[styles.formCard, "mb-[20px]"].join(" ")}>
          <div
            className={[GlobalClasses.title, "title"].join(" ")}>{(isEdit && !isDetail) ? "编辑" : isAdd ? "新增" : ""}员工加减分申请{isDetail ? "详情" : ""}</div>
          <Form form={form} layout={"vertical"} autoComplete="off">
            <Row>
              <Col span={6}>
                <Form.Item
                  label={"单据编号"}
                  name="code"
                >
                  <Input disabled></Input>
                </Form.Item>
                <Form.Item
                  label={"考核频次"}
                  name="evaluFrequency"
                  rules={[{ required: true, message: '请选择考核频次!' }]}
                >
                  <Select placeholder="请选择考核频次" disabled={isDetail} onChange={(value)=>{
                    switch (value) {
                      case 'YEAR':
                        setEvaluPersionType(1)
                        break;
                      case 'QUARTER':
                        setEvaluPersionType(2)
                        break;
                      case 'MONTH':
                        setEvaluPersionType(3)
                        break;
                      default:
                      break;
                    }
                  }} options={[
                    { value: 'YEAR', label: '年度' },
                    { value: 'QUARTER', label: '季度' },
                    { value: 'MONTH', label: '月度' },
                  ]} />
                </Form.Item>
              </Col>
              <Col span={6} offset={2}>
                <Form.Item
                  label={"申请人"}
                  name="personName"
                >
                  <Input disabled></Input>
                </Form.Item>
                <Form.Item
                  label={"考核期间"}
                  name="evaluPersion"
                  rules={[{ required: true, message: '请选择考核期间!' }]}
                >
                  <DatePicker picker={`${evaluPersionType==1?'year':evaluPersionType==2?'quarter':'month'}`} onChange={(value)=>{
                    if(form.getFieldValue().evaluFrequency){
                      switch (evaluPersionType) {
                        case 1:
                          console.log(dayjs(value).format('YYYY'));
                          break;
                        case 2:
                          console.log(dayjs(value).format('YYYY')+ '-Q' + dayjs(dayjs(value).format('YYYY-MM-DD')).quarter());
                          break;
                        case 3:
                          console.log(dayjs(value).format('YYYY-MM'));
                          break;
                      
                        default:
                          break;
                      }
                    }else{
                      message.error('请先选择考核频次');
                    }
                  }} disabled={isDetail}/>
                </Form.Item>
              </Col>
              <Col span={6} offset={2}>
                <Form.Item
                  label={"所属部门"}
                  name="deptName"
                >
                  <Input disabled></Input>
                </Form.Item>
              </Col>
            </Row>
          </Form>
          

          <Divider className={'mb-[20px] mt-0'} />

          <div className="header">
            <div className={[GlobalClasses.subTitle, 'title'].join(" ")}>--申请明细列表--</div>
            {
              !(isAdd || isEdit) ?
                null :
                (
                  <Row justify={"end"} className={"mb-[20px]"}>
                    {/*<Button type={"link"} icon={<DownloadOutlined/>}>下载模板</Button>*/}
                    {/*<Button type={"link"} icon={<DownloadOutlined/>}>导入</Button>*/}
                    <Space>
                      <Button type={'primary'} icon={<PlusOutlined />} onClick={() => {
                        setCurrentEdit({});
                        getProjectItem();
                        editForm.resetFields();
                        setOpen(true);
                      }}>新增</Button>
                    </Space>
                  </Row>
                )
            }
          </div>

          <Table
            rowKey={'itemCode'}
            dataSource={applicationData}
            columns={isDetail?applicationColumns:applicationColumns.concat(operateColumns)}
          ></Table>

          <Row justify={'end'}>
            <Space>
              <Button onClick={()=>Router.push('/performanceAppraise/employeePointsApply')}>取消</Button>
              {
                !(isAdd || isEdit) ?
                  null :
                <>
                  <Button onClick={save}>保存</Button>
                  <Button type={'primary'} onClick={submit}>提交</Button>
                </>
              }
            </Space>
          </Row>

          <Modal
            open={open}
            title={`${JSON.stringify(currentEdit) === "{}" ? "新增" : "编辑"}考核计算公式配置`}
            afterClose={() =>{
              setCurrentEdit({});
              setTimeout(() => {
                editForm.resetFields()
              }, 500);
            }}
            onOk={handleOk}
            onCancel={handleCancel}
            okText={'提交'}
            cancelText={'取消'}
            footer={(_, { OkBtn, CancelBtn }) => (
              <>
                <CancelBtn />
                <OkBtn />
              </>
            )}
          >
            <Form form={editForm} initialValues={currentEdit} labelCol={{span: 4}}>
              <Form.Item
                label={'项目名称'}
                name={'itemId'}
                rules={[{ required: true, message: '请选择项目名称!' }]}
              >
                <Select
                  placeholder={"请选择项目名称"}
                  options={projectList}
                  onChange={(value,option)=>{
                    setProjectName(option.label);
                    setProjectCode(option.code);
                    editForm.setFieldValue('itemDesc',option.projectDescription)
                    editForm.setFieldValue('finishDesc',option.projectDescription)
                    editForm.setFieldValue('praiseDesc',option.projectDescription)
                    editForm.setFieldValue('reqScore',100)
                    editForm.setFieldValue('reqDesc',option.projectDescription)
                  }}
                ></Select>
              </Form.Item>
              <Form.Item
                label={'项目内容'}
                name={'itemDesc'}
              >
                <Input placeholder={"请输入"} disabled></Input>
              </Form.Item>
              <Form.Item
                label={'完成情况'}
                name={'finishDesc'}
                rules={[{ required: true, message: '请输入完成情况!' }]}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'表彰情况'}
                name={'praiseDesc'}
                rules={[{ required: true, message: '请输入表彰情况!' }]}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
              <Form.Item
                label={'申请分数'}
                name={'reqScore'}
                rules={[{ required: true, message: '请输入申请分数!' }]}
              >
                <InputNumber className={'w-full'} min={0} placeholder={"请输入"}/>
              </Form.Item>
              <Form.Item
                label={'申请说明'}
                name={'reqDesc'}
                rules={[{ required: true, message: '请输入申请说明!' }]}
              >
                <Input placeholder={"请输入"}></Input>
              </Form.Item>
            </Form>
          </Modal>
        </div>
      </PageContainer>
    </>
  )
}

export const getServerSideProps = getLayoutProps;
export default EmployeePointsApplyCU;
